package com.sq.partner.manager.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.mybatis.model.ChannelDto;
import com.sq.partner.manager.mybatis.model.FacadeUser;
import com.sq.partner.manager.mybatis.model.FacadeUserChannel;
import com.sq.partner.manager.mybatis.model.GatewayAgency;
import com.sq.partner.manager.mybatis.model.GatewayChannelInfo;
import com.sq.partner.manager.mybatis.model.GatewaySubChannel;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.service.IFacadeUserChannelService;
import com.sq.partner.manager.service.IFacadeUserService;
import com.sq.partner.manager.service.IGatewayAgencyInfoConfigService;
import com.sq.partner.manager.service.IGatewayChannelInfoConfigService;
import com.sq.partner.manager.service.IGatewaySubChannelService;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.MD5Util;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.PasswordUtil;
import com.sq.partner.manager.util.StrUtil;

/**
 * 界面出单用户维护
 * @author zhihuizhao
 *
 */
@Controller
@RequestMapping(value="/facadeManager")
public class FacadeUserController {

	private static Logger logger = LogUtil.getLog(FacadeUserController.class);
	
	@Resource
	private IFacadeUserService userService;
	@Resource
	private IFacadeUserChannelService channelService;
	@Resource
	private IGatewaySubChannelService subChannelService;
	@Resource
	private IGatewayChannelInfoConfigService channelInfoConfigService;
	@Resource
	private IGatewayAgencyInfoConfigService agencyInfoConfigService;
	
	
	/**
	 * 展示出单用户维护页面
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/user")
	public String showFacadeUserList(HttpServletRequest request) throws Exception{
		return "facadeManage/facadeUserManage";
	}
	
	/**
	 * 页面初始化加载所有用户列表
	 * @param size
	 * @param pageIndex
	 * @param user
	 * @param userName
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/initFacadeUsers")
	public @ResponseBody Page initAllUsers(HttpSession session,Integer size,Integer pageIndex,FacadeUser user,String userName,String userCode,String userTypeCode,String fKSubChannelCode,String agencyCode) throws Exception
	{
		if(StrUtil.isNotEmpty(userName)){
			user.setUserName(userName);
		}
		if(StrUtil.isNotEmpty(userCode)){
			user.setUserCode(userCode);
		}
		if(StrUtil.isNotEmpty(userTypeCode)){
			user.setUserTypeCode(userTypeCode);
		}
		if(StrUtil.isNotEmpty(fKSubChannelCode)){
			user.setfKSubChannelCode(fKSubChannelCode);
		}
		if(StrUtil.isNotEmpty(agencyCode)){
			user.setAgencyCode(agencyCode);
		}
		Page page=new Page();
		page.setCurrent(pageIndex);
		//总行和分行
		boolean isHQFlag = false;
		GatewayUser userDept = (GatewayUser) session.getAttribute(Constants.SESSION_USER);
		if(null != userDept && StrUtil.isNotEmpty(userDept.getDepartmentStr())){
			isHQFlag = userDept.getDepartmentStr().contains(Constants.HQ_BRANCH_CODE);
			user.setDepartmentStr(userDept.getDepartmentStr());
		}
		user.setHQFlag(isHQFlag);
		Page p = userService.queryPage(page,pageIndex,user);
		return p;
	}


	
	/**
	 * 新增用户之前：校验输入的用户名是否已经存在，如果存在则提示用户已存在，重新输入；
	 * 如果不存在，校验该用户名是否已经在UM系统中配置，如果有则允许添加，没有则提示用户
	 * 先在UM系统中配置该用户，然后进行此操作
	 * @param req
	 * @param user
	 * @param usercode
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/queryUsercodeIsExists")
	public @ResponseBody Result checkUsercodeBeforeAdd(HttpServletRequest req,FacadeUser user,String usercode) throws Exception {
		Map<String,String> map = new HashMap<String, String>();
		map.put("userCode", usercode);
		FacadeUser ur = (FacadeUser)userService.queryUserCountByMap(map);
		if(ur!=null){
			logger.info("---------------用户名已存在------------------");
			return Result.error("该用户名已存在");
		}else{
			return null;
		}
/*		else{
			Object obj = UMClient.getUser(usercode);
			if(obj==null){
				return Result.error("notexist");
			}else{
				return null;
			}
		}
*/	}
	
	
	
	/**
	 * 新增用户  输入的用户名如果系统中已存在，则提示信息，重新输入
	 * @param user
	 * @param username
	 * @param email
	 * @param usercode
	 * @param telephone
	 * @param status
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/addUser")
	public @ResponseBody Result addUser(HttpSession session, HttpServletRequest req,FacadeUser user,String username,String email,String usercode,String telephone,Integer status, String fKSubChannelCode,String userTypeCode,String agencyCode) throws Exception {
		if(StrUtil.isEmpty(userTypeCode)){
			return Result.error("用户类型不能为空");
		}
		if(!("1".equals(userTypeCode) || "2".equals(userTypeCode) || "4".equals(userTypeCode))){
			return Result.error("操作失败，系统检查出用户类型非法数据传入，请修改！");
		}
		if(StrUtil.isEmpty(username)){
			return Result.error("姓名不能为空");
		}
		if(StrUtil.isEmpty(usercode)){
			return Result.error("用户名不能为空");
		}
		Map<String, String> map1=new HashMap<String, String>();
		map1.put("subChannelCode", fKSubChannelCode);
		map1.put("chanelCode", user.getFkChannelCode());
		if("1".equals(userTypeCode)){
			if(StrUtil.isEmpty(fKSubChannelCode)){
				return Result.error("所属机构不能为空");
			}
			if(!checkIsHasPrivilege(session,map1))
			{
				return Result.error("权限不足，无权操作该合作伙伴用户!");
			}
		}
		if("2".equals(userTypeCode)){
			if(StrUtil.isEmpty(agencyCode)){
				return Result.error("所属中介公司不能为空");
			}
			if(!checkAgencyIsHasPrivilege(session, agencyCode)){
				return Result.error("权限不足，无权操作该中介公司用户!");
			}
		}
		
		if(StrUtil.isEmpty(telephone)){
			return Result.error("用户电话不能为空");
		}
		String reg = "\\d{7,20}";
		if(!(telephone.matches(reg))){
			return Result.error("用户电话格式不正确：只能录入不小于七位数的数字");
		}
		Map<String,String> map = new HashMap<String, String>();
		map.put("userCode", usercode);
		FacadeUser ur = (FacadeUser)userService.queryUserCountByMap(map);
		if(ur!=null){
			logger.info("---------------用户名已存在------------------");
			return Result.error("该用户名已存在");
		}else
		{
/*			Object obj = UMClient.getUser(usercode);
			if(obj==null){
				return Result.error("notexist");
			}else{
*/				String password = PasswordUtil.getPassword();
				user.setUserPwd(MD5Util.md5(password));
				user.setUserCode(usercode);
				user.setUserName(username);
				user.setEmail(email);
				user.setTelephone(telephone);
				user.setStatus(new Integer(1));
				user.setOperUser(getSessionUser(req).getUserid());
				user.setOperTime(new Date());
				
				if(userService.addUser(user)){
					logger.info("新增用户成功,初始密码是:<a style=\"color:red\">"+password+"</a>请牢记!");
					return Result.success("新增成功,初始密码是:<a style=\"color:red\">"+password+"</a>请牢记!");
				}else{
					logger.info("新增用户失败");
					return Result.error("新增失败");
				}
//			}
		}
	}

	
	/**
	 * 根据用户id获取用户信息
	 * @param userid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/queryUserById")
	public @ResponseBody FacadeUser getUserInfoById(Long userid) throws Exception{
		if(null==userid){
			return null;
		}else{
			return userService.queryUserById(userid);
		}
	}
	
	/**
	 * 修改用户信息
	 * @param req
	 * @param user
	 * @param userid
	 * @param username
	 * @param channel
	 * @param email
	 * @param telephone
	 * @param status
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/editUser")
	public @ResponseBody Result updateUser(HttpSession session,HttpServletRequest req,FacadeUser user,Long userid,String username,String email,String telephone,Integer status,String fKSubChannelCode,String userTypeCode, String agencyCode) throws Exception {
		if(StrUtil.isEmpty(userTypeCode)){
			return Result.error("用户类型不能为空");
		}
		if(!("1".equals(userTypeCode) || "2".equals(userTypeCode) || "4".equals(userTypeCode))){
			return Result.error("操作失败，系统检查出用户类型非法数据传入，请修改！");
		}
		if(StrUtil.isEmpty(username)){
			return Result.error("姓名不能为空");
		}
		if("1".equals(userTypeCode)){
			if(StrUtil.isEmpty(fKSubChannelCode)){
				return Result.error("所属机构不能为空");
			}
			Map<String, String> map1=new HashMap<String, String>();
			map1.put("subChannelCode", fKSubChannelCode);
			map1.put("chanelCode", user.getFkChannelCode());
			if(!checkIsHasPrivilege(session,map1))
			{
				return Result.error("权限不足，无权操作该合作伙伴用户!");
			}
		}
		if("2".equals(userTypeCode)){
			if(StrUtil.isEmpty(agencyCode)){
				return Result.error("所属中介公司不能为空");
			}
			if(!checkAgencyIsHasPrivilege(session, agencyCode)){
				return Result.error("权限不足，无权操作该中介公司用户!");
			}
		}
		if(StrUtil.isEmpty(telephone)){
			return Result.error("用户电话不能为空");
		}
		String reg = "\\d{7,20}";
		if(!(telephone.matches(reg))){
			return Result.error("用户电话格式不正确：只能录入不小于七位数的数字");
		}
		user.setUserid(userid);
		user.setUserName(username);
		user.setEmail(email);
		user.setTelephone(telephone);
		user.setStatus(status);
		user.setOperUser(getSessionUser(req).getUserid());
		user.setfKSubChannelCode(fKSubChannelCode);
		user.setUserTypeCode(userTypeCode);
		user.setAgencyCode(agencyCode);
		user.setOperTime(new Date());
		boolean flag = userService.updateUser(user);
		if(flag){
			return Result.success("修改成功");
		}else{
			return Result.error("修改失败");
		}
		
	}
	
	
	/**
	 * 删除用户（删除用户后，删除与该用户关联的所有合作伙伴）
	 * @param req
	 * @param channel
	 * @param userid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/delUser")
	public @ResponseBody Result updateUser(HttpSession session,HttpServletRequest req,FacadeUserChannel channel, Long userid,String fKSubChannelCode,String userTypeCode,String agencyCode,String channelCode) throws Exception {
		if(StrUtil.isEmpty(userTypeCode)){
			return Result.error("用户类型不能为空");
		}
		if(!("1".equals(userTypeCode) || "2".equals(userTypeCode) || "4".equals(userTypeCode))){
			return Result.error("操作失败，系统检查出用户类型非法数据传入，请修改！");
		}
		if("1".equals(userTypeCode)){
			if(StrUtil.isEmpty(fKSubChannelCode)){
				return Result.error("所属机构不能为空");
			}
			Map<String, String> map1=new HashMap<String, String>();
			map1.put("subChannelCode", fKSubChannelCode);
			map1.put("chanelCode", channelCode);
			if(!checkIsHasPrivilege(session,map1))
			{
				return Result.error("权限不足，无权操作该合作伙伴用户!");
			}
		}
		if("2".equals(userTypeCode)){
			if(StrUtil.isEmpty(agencyCode)){
				return Result.error("所属中介公司不能为空");
			}
			if(!checkAgencyIsHasPrivilege(session, agencyCode)){
				return Result.error("权限不足，无权操作该中介公司用户!");
			}
		}
		if(null==userid){
			return Result.error("删除失败，用户Id不能为空");
		}else{
			channel.setUserId(userid);
			channelService.delete(userid);
			boolean flag = userService.delUserById(userid);
			if(flag){
				return Result.success("删除成功");
			}else{
				return Result.error("删除失败");
			}
		}
	}
	
	/**
	 * 重置密码
	 * @param user
	 * @param userid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/resetPwd")
	public @ResponseBody Result resetPassword(HttpServletRequest req,FacadeUser user,Long userid) throws Exception {
		user.setUserid(userid);
		user.setOperTime(new Date());
		user.setOperUser(getSessionUser(req).getUserid());
		String password = PasswordUtil.getPassword();
		user.setUserPwd(MD5Util.md5(password));
		user.setLoginFirst("1");
		user.setLoginCounter(0);
		boolean flag = userService.saveUser(user);
		if(flag){
			return Result.success("密码重置成功，密码是:<a style=\"color:red\">"+password+"</a><br>请通知该用户尽快修改密码!");
		}else{
			return Result.error("密码重置失败");
		}
	}
	
	
	
	@RequestMapping(value="/initChannelTree")
	public @ResponseBody Page<GatewaySubChannel> queryChannelList(HttpServletRequest req,GatewayUser user,GatewaySubChannel sub,Integer size,int pageIndex) throws Exception {
		user = getSessionUser(req);
		//总行和分行
		Page<GatewaySubChannel> page = new Page<GatewaySubChannel>();
		page.setCurrent(pageIndex);
		page.setSize(size);
		page.setType(sub);
		boolean isHQFlag = false;
		if(null != user && StrUtil.isNotEmpty(user.getDepartmentStr())){
			isHQFlag = user.getDepartmentStr().contains(Constants.HQ_BRANCH_CODE);
		}
		user.setHQFlag(isHQFlag);
		return  userService.queryChannelListByDeptForTree(user,page);
	}
	
	
	/**
	 * 出单用户配置合作伙伴
	 * @param req
	 * @param userChannel
	 * @param userId
	 * @param channelCodeStr
	 * @return
	 * @throws Exception
	 */
	/*@RequestMapping(value="/bindChannelToUser")
	public @ResponseBody Result bindChannelToUser(HttpServletRequest req,FacadeUserChannel userChannel,Long userId,String channelCodeStr) throws Exception{
		if(userId!=null){
			userChannel.setUserId(userId);
			if(StrUtil.isNotEmpty(channelCodeStr)){
				//删除该角色下所有菜单
				channelService.delete(userId);
					String [] channelArr = channelCodeStr.split(",");
					//循环添加菜单
					for(int i=0;i<channelArr.length;i++){
						FacadeUserChannel rm = new FacadeUserChannel();
						rm.setUserId(userId);
						rm.setChannelCode(channelArr[i]);
						rm.setOperTime(new Date());
						rm.setStatus("1");
						rm.setOperUser(((GatewayUser)getSessionUser(req)).getUserid());
						channelService.add(rm);
					}
					return Result.success("配置合作伙伴成功");
				
			}else{
				return Result.error("请至少选择一个合作伙伴");
			}
		}else{
			return Result.fail("配置失败，无法获取用户ID");
		}
	}*/
	
	/**
	 * 获取用户已配置的合作伙伴
	 * @param req
	 * @param channel
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/getChannelsOfCurUser")
	public @ResponseBody List<ChannelDto> queryDeptsOfcurUser(HttpServletRequest req,FacadeUserChannel channel,Long userId) throws Exception{
		if(null!=userId){
			channel.setUserId(userId);
			List<ChannelDto> list = channelService.queryChannelsByUserid(channel);
			return list;
		}
		return null;
	}

	/**
	 * 获取session中的User
	 * @param req
	 * @return
	 */
	public static GatewayUser getSessionUser(HttpServletRequest req){
		HttpSession session = req.getSession();
		GatewayUser u = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		return u;
	}

	// 校验用户是否有权限操作
	private boolean checkIsHasPrivilege(HttpSession session,Map<String, String> map)
			throws Exception {
		GatewaySubChannel subChannel = subChannelService
				.querySubChannelInfoByCondition(map);
		if (null != subChannel
				&& StrUtil.isNotEmpty(subChannel.getFkChannelCode())) {
			GatewayChannelInfo channelInfo = channelInfoConfigService
					.queryChannelInfoByChannelCode(subChannel
							.getFkChannelCode());
			if (null != channelInfo
					&& StrUtil.isNotEmpty(channelInfo.getDeptCode())) {
				return channelInfoConfigService.checkIsHasPrivilege(session,
						channelInfo.getDeptCode());
			}
			return false;
		}
		return false;
	}
	
	// 校验用户是否有权限操作 中介公司
	private boolean checkAgencyIsHasPrivilege(HttpSession session, String param) throws Exception {
		GatewayAgency tem = new GatewayAgency();
		tem.setAgencyCode(param);
		GatewayAgency ga = agencyInfoConfigService.queryAgencyInfoByCode(tem);
		if (null != ga && StrUtil.isNotEmpty(ga.getDeptCode())) { 
			return channelInfoConfigService.checkIsHasPrivilege(session,ga.getDeptCode());
		}
		return false;
	}
	
	/**
	 * 用户解锁
	 * @param user
	 * @param userid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/unlock")
	public @ResponseBody Result unlock(HttpServletRequest req,FacadeUser user,Long userid) throws Exception {
		user.setUserid(userid);
		user.setOperTime(new Date());
		user.setOperUser(getSessionUser(req).getUserid());
		user.setLoginCounter(0);
		boolean flag = userService.saveUser(user);
		if(flag){
			return Result.success("用户解锁成功");
		}else{
			return Result.error("用户解锁失败");
		}
	}
}